package com.okq.action;

import com.okq.action.base.BaseActionSupport;
import com.okq.entity.*;
import com.okq.service.*;
import com.okq.util.BaseTool;
import com.okq.util.Constant;
import com.okq.util.PublicClass;
import com.okq.util.TimeTool;
import com.okq.util.page.Page;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.PrintWriter;
import java.util.*;

/**
 * 描述 : 生产管理
 * 作者 : zdl
 * 日期 : 2017/7/14 17:05
 */
public class ProductionAction extends BaseActionSupport {

    private static final long serialVersionUID = 2682137847147961985L;
    /**
     * 生产接口
     */
    @Autowired
    private IProductionService productionServiceImpl;
    /**
     * 产品接口
     */
    @Autowired
    private IProductService productServiceImpl;
    /**
     * 数据字典接口
     */
    @Autowired
    private IDictService dictServiceImpl;
    /**
     * 用户接口
     */
    @Autowired
    private IUserService userServiceImpl;
    /**
     * 系统日志接口
     */
    @Autowired
    private ILogService logServiceImpl;
    /**
     * 日志
     */
    private static final Logger logger = Logger.getLogger(ProductionAction.class);
    /**
     * 分页开始条数
     */
    private int iDisplayStart;

    /**
     * 每页显示条数
     */
    private int iDisplayLength;
    private String id;
    private String type;
    private Production production;

    /**
     * 获取生产分页列表
     *
     * @return json
     */
    public String getProductionList() {
        PrintWriter out = null;
        try {
            out = this.getResponse().getWriter();
            User loginUser = (User) getSession().getAttribute("loginUser");
            if (loginUser != null) {
                if (iDisplayLength == 0) {
                    iDisplayLength = -1;
                }
                int pageNum = (int) (Math.ceil(iDisplayStart / iDisplayLength)) + 1;
                /* 分页信息 */
                Page<Production> pageInfo = new Page<>(iDisplayLength);
                pageInfo.setPageNo(pageNum);
                pageInfo = productionServiceImpl.pageByProduction(pageInfo, production);
                int iTotalRecords = pageInfo.getTotalCount();
                int iTotalDisplayRecords = pageInfo.getTotalCount() < 0 ? 0 : pageInfo.getTotalCount();
                /* 得到结果 */
                List<Production> pList = pageInfo.getResult();
                /* 封装list */
                List<Map<String, Object>> pMapList = new ArrayList<>();
                if (pList != null && !pList.isEmpty() && pList.size() > 0) {
                    int i = (pageNum - 1) * iDisplayLength + 1;
                    for (Production p : pList) {
                        Map<String, Object> map = new HashMap<>();
                        map.put("no", i);// 序号
                        map.put("id", p.getId());
                        map.put("batch", StringUtils.defaultString(p.getBatch(), ""));
                        map.put("productTypeStr", dictServiceImpl.getDictByValueAndType(p.getProductType(), Constant.PRODUCT_TYPE));
                        Integer overdue = 0;
                        String startTime = StringUtils.defaultString(p.getStartTime(), "");
                        if (StringUtils.isNotBlank(startTime)) {
                            Date nowDate = new Date();
                            Date startDate = TimeTool.stringToDate(startTime, "yyyy-MM-dd HH:mm:ss");
                            if (startDate.getTime() < nowDate.getTime()) {
                                overdue = 1;//逾期未开始
                            }
                        }
                        map.put("overdue", overdue);
                        map.put("startTime", startTime);
                        map.put("entTime", StringUtils.defaultString(p.getEntTime(), ""));
                        map.put("number", p.getNumber() != null ? p.getNumber() : "");
                        map.put("qualified", p.getQualified() != null ? p.getQualified() : "");
                        map.put("remark", StringUtils.defaultString(p.getRemark(), ""));
                        String stateStr = "";
                        Integer state = p.getState();
                        map.put("state", state);
                        if (state != null) {
                            switch (state) {
                                case 0:
                                    stateStr = "未开始";
                                    break;
                                case 1:
                                    stateStr = "进行中";
                                    break;
                                case 2:
                                    stateStr = "已完成";
                                    break;
                                case 3:
                                    stateStr = "已质检";
                                    break;
                                case 4:
                                    stateStr = "已入库";
                                    break;
                                default:
                                    break;
                            }
                        }
                        map.put("stateStr", stateStr);
                        String chargeId = p.getChargeId();
                        String chargeName = "";
                        if (StringUtils.isNotBlank(chargeId)) {
                            User u = userServiceImpl.getUserById(chargeId);
                            if (u != null) {
                                chargeName = StringUtils.defaultString(u.getUserName(), "");
                            }
                        }
                        map.put("chargeName", chargeName);
                        pMapList.add(map);
                        i++;
                    }
                }
                Map<String, Object> jsonMap = new HashMap<>();
                jsonMap.put("iTotalRecords", iTotalRecords);
                jsonMap.put("iTotalDisplayRecords", iTotalDisplayRecords);
                jsonMap.put("aaData", pMapList);

                String json = BaseTool.toJson(jsonMap);
                out.print(json);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        } finally {
            if (out != null) {
                out.close();
            }
        }
        return null;
    }

    /**
     * 删除
     *
     * @return 成功标识
     */
    public String deleteProduction() {
        PrintWriter out = null;
        try {
            out = this.getResponse().getWriter();
            User loginUser = (User) getSession().getAttribute("loginUser");
            if (loginUser != null && StringUtils.isNotBlank(id)) {
                Production p = productionServiceImpl.getProductionById(id);
                if (p != null) {
                    p.setIsDelete(1);
                    productionServiceImpl.updateProduction(p);
                    //同时删除生产对应的所有产品
                    List<Product> proList = productServiceImpl.listProductByPid(p.getId());
                    if (proList != null && !proList.isEmpty() && proList.size() > 0) {
                        for (Product pro : proList) {
                            pro.setIsDelete(1);
                            productServiceImpl.updateProduct(pro);
                        }
                    }
                    out.print(0);
                    //添加系统日志
                    String userName = loginUser.getUserName();
                    String nowTime = TimeTool.getNowTime();
                    String content = "用户：" + userName + "，于" + nowTime + " 删除生产信息，批次：" + p.getBatch() + "！";
                    PublicClass.addLog(userName, loginUser.getLoginName(), "生产管理", 2, content, logServiceImpl);
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        } finally {
            if (out != null) {
                out.close();
            }
        }
        return null;
    }

    /**
     * 跳转
     *
     * @return 类型
     */
    public String toUpdateOrDetail() {
        try {
            User loginUser = (User) getSession().getAttribute("loginUser");
            if (loginUser != null && StringUtils.isNotBlank(id)) {
                production = productionServiceImpl.getProductionById(id);
                if (production != null && type.equals("update")) {
                    return "update";
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        }
        return null;
    }

    /**
     * 保存
     *
     * @return 成功标识
     */
    public String saveProduction() {
        PrintWriter out = null;
        try {
            out = this.getResponse().getWriter();
            User loginUser = (User) getSession().getAttribute("loginUser");
            if (loginUser != null && production != null) {
                if (StringUtils.isNotBlank(type) && type.equals("add")) {// 新增
                    String pId = BaseTool.getPK();
                    production.setId(pId);
                    String batch = getBatch();
                    production.setBatch(batch);
                    String userName = loginUser.getUserName();
                    if (StringUtils.isNotBlank(userName)) {
                        production.setCreateUserId(loginUser.getId());
                        production.setCreateUserName(userName);
                    }
                    String comCode = loginUser.getComCode();
                    if (StringUtils.isNotBlank(comCode)) {
                        production.setComCode(comCode);
                    }
                    productionServiceImpl.saveProduction(production);
                    boolean addProduct = addProducts(pId, batch, production.getProductType(), production.getNumber(), loginUser);
                    if (addProduct) {
                        out.print("success");
                    } else {
                        out.print("error");
                    }
                    //添加系统日志
                    String nowTime = TimeTool.getNowTime();
                    String content = "用户：" + userName + "，于" + nowTime + " 添加生产信息，批次：" + batch + "！";
                    PublicClass.addLog(userName, loginUser.getLoginName(), "生产管理", 2, content, logServiceImpl);
                } else if (StringUtils.isNotBlank(type) && type.equals("update")) {// 修改
                 
                	Production oldProduction = productionServiceImpl.getProductionById(production.getId());
                    if (oldProduction != null) {
                        oldProduction.setProductType(production.getProductType());
                        oldProduction.setStartTime(production.getStartTime());
                        oldProduction.setNumber(production.getNumber());
                        oldProduction.setChargeId(production.getChargeId());
                        oldProduction.setRemark(production.getRemark());
                        String userName = loginUser.getUserName();
                        if (StringUtils.isNotBlank(userName)) {
                            oldProduction.setUpdateUserId(loginUser.getId());
                            oldProduction.setUpdateUserName(userName);
                        }
                        productionServiceImpl.updateProduction(oldProduction);
                        out.print("success");
                        //添加系统日志
                        String nowTime = TimeTool.getNowTime();
                        String content = "用户：" + userName + "，于" + nowTime + " 修改生产信息，批次：" + oldProduction.getBatch() + "！";
                        PublicClass.addLog(userName, loginUser.getLoginName(), "生产管理", 2, content, logServiceImpl);
                    }
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        } finally {
            if (out != null) {
                out.close();
            }
        }
        return null;
    }

    /**
     * 添加生产对应的产品信息
     *
     * @param pId         生产Id
     * @param batch       生产批次
     * @param productType 产品类型
     * @param number      生产数量
     * @param loginUser   登录用户
     */
    private boolean addProducts(String pId, String batch, Integer productType, Integer number, User loginUser) {
        boolean addProduct = false;
        try {
            if (StringUtils.isNotBlank(pId) && StringUtils.isNotBlank(batch) && productType > -1 && number > 0 && loginUser != null) {
                Production p = productionServiceImpl.getProductionById(pId);
                if (p != null) {
                    for (int i = 0; i < number; i++) {
                        Product pro = new Product();
                        pro.setId(BaseTool.getPK());
                        pro.setProductionId(pId);
                        pro.setProductType(productType);
                        pro.setCode(getProductCode(i, batch, productType));
                        String productName = "";
                        String dictName = dictServiceImpl.getDictByValueAndType(productType, Constant.PRODUCT_TYPE);
                        if (StringUtils.isNotBlank(dictName)) {
                            productName = dictName + "设备" + String.format("%03d", i + 1);
                        }
                        pro.setName(productName);
                        String userName = loginUser.getUserName();
                        if (StringUtils.isNotBlank(userName)) {
                            pro.setCreateUserName(userName);
                        }
                        pro.setCreateUserId(loginUser.getId());
                        pro.setComCode(loginUser.getComCode());
                        productServiceImpl.saveProduct(pro);
                        addProduct = true;
                    }
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return addProduct;
    }

    /**
     * 获取产品编号
     *
     * @param i           起始值
     * @param batch       批次
     * @param productType 产品类型
     * @return productCode
     */
    public static String getProductCode(int i, String batch, Integer productType) {
        batch = batch.substring(1, batch.length());
        String typeStr;
        if (productType.toString().length() == 1) {
            typeStr = "0" + productType;
        } else {
            typeStr = productType.toString();
        }
        String productCode = BaseTool.getPropertiesValue("config.properties", "productCode");
        if (StringUtils.isBlank(productCode)) {
            productCode = "okq";
        }
        return productCode + typeStr + batch + String.format("%03d", i + 1);
    }

    /**
     * 获取批次号
     *
     * @return 批次号
     */
    private String getBatch() {
        String batchCode = "";
        try {
            Production p = productionServiceImpl.getLastProduction();
            if (p != null) {
                String batch = p.getBatch();
                if (StringUtils.isNotBlank(batch)) {
                    String oldBatchDate = batch.substring(1, 7);
                    String nowDate = TimeTool.formatDate(new Date(), "yyyyMM");
                    if (oldBatchDate.equals(nowDate)) {
                        Integer codeNum = Integer.valueOf(batch.substring(7, batch.length()));
                        batchCode = batch.substring(0, 7) + BaseTool.zeroFormat("000", codeNum + 1);
                    } else {
                        batchCode = getDefaultBatch();
                    }
                } else {
                    batchCode = getDefaultBatch();
                }
            } else {
                batchCode = getDefaultBatch();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return batchCode;
    }

    /**
     * 生成默认批次号
     *
     * @return 批次号
     */
    private String getDefaultBatch() {
        int _suffix = 0;
        String strTmp = TimeTool.formatDate(new Date(), "yyyyMM");
        _suffix++;
        if (_suffix > 999) {
            _suffix = 0;
        }
        String batchCode = BaseTool.getPropertiesValue("config.properties", "batch");
        if (StringUtils.isBlank(batchCode)) {
            batchCode = "P";
        }
        strTmp = batchCode + strTmp + String.format("%03d", _suffix);
        return strTmp;
    }


    public int getIDisplayStart() {
        return iDisplayStart;
    }

    public void setIDisplayStart(int iDisplayStart) {
        this.iDisplayStart = iDisplayStart;
    }

    public int getIDisplayLength() {
        return iDisplayLength;
    }

    public void setIDisplayLength(int iDisplayLength) {
        this.iDisplayLength = iDisplayLength;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public Production getProduction() {
        return production;
    }

    public void setProduction(Production production) {
        this.production = production;
    }
}
